<template>
    <el-container class="pageContainer">
        <el-container class="mapAndListBox">
            <el-main class="mapBox">
                <div id="cesiumContainer" />
            </el-main>

            <el-aside class="listBox">
                <ListPage @clickGarden="gardenClick" />
            </el-aside>
        </el-container>

        <el-footer class="statisticsBox">
            <Statistics :gardenId="gardenId" />
        </el-footer>
    </el-container>
</template>

<script setup lang="ts">
import {onMounted, ref}                       from 'vue'
import * as Cesium                            from "cesium";
import 'cesium/Build/CesiumUnminified/Widgets/widgets.css'
import {list as getList, mapurl as getMapUrl} from "@/api/garden";
import ListPage                               from "./list/index.vue"
import Statistics                             from "./statistics/index.vue"

var viewer: Cesium.Viewer | null = null;

const gardenId = ref("")


/**
 * 列表点击跳转
 */
function gardenClick(garden: any) {
    gardenId.value = garden.id

    //获取lngLat
    const [longitudeStr, latitudeStr] = garden.lngLat.split(',');

    const longitudebd = parseFloat(longitudeStr);
    const latitudebd  = parseFloat(latitudeStr);
    const {lng, lat}  = bMapTransQQMap(longitudebd, latitudebd);
    viewer.camera.setView({
        // Cesium的坐标是以地心为原点，一向指向南美洲，一向指向亚洲，一向指向北极州
        // fromDegrees()方法，将经纬度和高程转换为世界坐标
        destination: Cesium.Cartesian3.fromDegrees(lng, lat, 30000),
        orientation: {
            // 指向
            heading: 6.283185307179581,
            // 视角
            pitch: -1.5688168484696687,
            roll : 0.0
        }
    });
}

function bMapTransQQMap(lng: number, lat: number) {
    let x_pi      = 3.14159265358979324 * 3000.0 / 180.0;
    let x         = lng - 0.0065;
    let y         = lat - 0.006;
    let z         = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    let theta     = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    let longitude = z * Math.cos(theta);
    let latitude  = z * Math.sin(theta);

    return {
        lng: longitude,
        lat: latitude
    }
}

function drawMarker(data: any[]) {
    data.map((value) => {
        if (value.lngLat === "") {
            return
        }
        //获取lngLat
        const [longitudeStr, latitudeStr] = value.lngLat.split(',');

        const longitudebd = parseFloat(longitudeStr);
        const latitudebd  = parseFloat(latitudeStr);
        const {lng, lat}  = bMapTransQQMap(longitudebd, latitudebd);

        viewer.entities.add({
            position : Cesium.Cartesian3.fromDegrees(
                lng,
                lat
            ),
            billboard: {
                image           : `images/location.png`,//图标地址
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,//原点位于对象的左侧。
                verticalOrigin  : Cesium.VerticalOrigin.BOTTOM,//原点位于对象的顶部。
                // disableDepthTestDistance: Number.POSITIVE_INFINITY,//禁用深度测试距离
                // pixelOffset: new Cesium.Cartesian2(-6, -32),//像素偏移
                // scale: 0.8,//比例
            },
            label    : {
                text            : value.name,
                style           : Cesium.LabelStyle.FILL_AND_OUTLINE, //有填充和边框
                font            : "16px bold ",
                scale           : 1,
                fillColor       : Cesium.Color.WHITE,
                outlineColor    : Cesium.Color.BLACK,
                outlineWidth    : 3,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,//对齐方式
                verticalOrigin  : Cesium.VerticalOrigin.TOP,//对齐方式
                pixelOffset     : new Cesium.Cartesian2(0, -46),//像素偏移
                // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND

            },
        });
    })
};


function init() {
    Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3NWEyMzk4Yi1kZGVlLTRhODAtOGYyYi02ZDk2NDNjMTc0ZTAiLCJpZCI6MTE2NTY4LCJpYXQiOjE2Njk3OTQwMjZ9.hKjQULNzZBWJTQG4FC-JyDXNQXOGs-hO4Ba4_eBUtWQ";

    viewer = new Cesium.Viewer("cesiumContainer", {
        geocoder            : false,
        homeButton          : false,
        sceneModePicker     : false,
        baseLayerPicker     : false,
        navigationHelpButton: false,
        animation           : false,
        timeline            : false,
        fullscreenButton    : false,
    });

    viewer.camera.setView({
        // Cesium的坐标是以地心为原点，一向指向南美洲，一向指向亚洲，一向指向北极州
        // fromDegrees()方法，将经纬度和高程转换为世界坐标
        destination: Cesium.Cartesian3.fromDegrees(112.962475, 28.195802, 300000),
        orientation: {
            // 指向
            heading: 6.283185307179581,
            // 视角
            pitch: -1.5688168484696687,
            roll : 0.0
        }
    });
    getMapUrl().then(res => {

        const mapurl = res?.data
        console.log(mapurl)
        console.log(viewer)
        viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
            url            : mapurl + "/{z}/{x}/{y}.png",
            layer          : 'tdtVecBasicLayer',
            style          : 'default',
            format         : 'image/png',
            tileMatrixSetID: 'GoogleMapsCompatible',
            show           : true,
        }));
    })
    // viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
    //     url            : "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
    //     layer          : 'tdtVecBasicLayer',
    //     style          : 'default',
    //     format         : 'image/png',
    //     tileMatrixSetID: 'GoogleMapsCompatible',
    //     show           : true,
    // }));
}

function loadData() {
    getList().then(res => {
        const sourceGardenList = res?.data
        drawMarker(sourceGardenList);
    }).finally(() => {

    })
}

onMounted(() => {
    init()
    loadData()
})

</script>

<style scoped>
.pageContainer {
    width: 100%;
    height: 100%;
}

.mapAndListBox {
    width: 100%;
    height: 50%;
}

.mapBox {
    height: 100%;

    #cesiumContainer {
        height: 100%;
    }
}

.listBox {
    height: 100%;
    width: 500px;
}

.statisticsBox {
    height: 50%;
}
</style>

